package com.atguigu.guli.service.oss.controller.admin;

import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.common.base.util.ExceptionUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * @className: FileController
 * @description: 文件上传控制器
 * @date: 2020/11/28
 * @author: cakin
 */
@Api(description = "阿里云文件管理")
@CrossOrigin
@RestController
@RequestMapping("/admin/oss/file")
@Slf4j
public class FileController {
    /**
     * 文件上传服务
     */
    @Autowired
    private FileService fileService;

    /**
     * 功能描述：文件上传控制器
     *
     * @param file   文件
     * @param module 文件夹
     * @return R 返回给前端的数据
     * @author cakin
     * @date 2020/11/28
     */
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "模块", required = true) @RequestParam("module") String module) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            // 抛出文件上传失败异常
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 功能描述：文件删除
     *
     * @param url 待删除文件的url
     * @return R 返回给调用者的消息
     * @author cakin
     * @date 2020/11/29
     */
    @ApiOperation(value = "文件删除")
    @DeleteMapping("remove")
    public R removeFile(@ApiParam(value = "要删除的文件url路径", required = true) @RequestBody String url) {
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }

    /**
     * 功能描述：测试OpenFeign
     *
     * @param
     * @return R 返回给消费者的消息
     * @author cakin
     * @date 2020/11/29
     * @description:
     */
    @ApiOperation(value = "测试")
    @GetMapping("test")
    public R test() {
        log.info("oss test被调用");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
